import { defineStore } from 'pinia';
import { messageFn } from '../../utils';
import { createLocalStorage } from '/@/utils/cache';
const ls = createLocalStorage();
import {
  userInfoApi, //查询账户详情
  userParamsApi, //获取用户列表相关参数
  userTagApi, //获取用户标签
  userPageApi, //分页查询账户列表
  contactQueryApi, //条件查询联系人
  userContactCreateApi, //创建联系人
  meteringAdminApi, //获取物理水表分页
  userLogoffApi, //注銷
  createApi, //创建账户
  updateApi, //修改账户
  bindContactApi, //账户绑定联系人
  companyListQueryApi, //条件查询企业
  userChangeHouseholderApi, //变更户主
  meteringCreateApi, //创建水表
  unbindMeterApi, //账户解绑水表
  unbindContactApi, //账户解绑联系人
  bindMeterApi, //账户绑定水表
  getCustomerUserRecordApi, //获取该账户的所有业务记录数量
  isContactApi,
  isMeterApi,
} from '/@/api/houseHold/accountDetails';

import {
  regionListApi, //省市区联动对应表
} from '/@/api/commonApi/index';

interface selectType {
  lable: string;
  value: string;
}
/*联系人*/
interface contactType {
  full_name: string; //全称
  gender: number; //性别
  cell_phone: string; //手机号
  certificate_code: string; //证件号
  certificate_type_id: number; //证件
  email: string; //邮箱
  home_address: string; //家庭住址
  home_address_region_id: number; //家庭住址区域id
}
/*水表类型*/
interface userMeterType {
  first_connection_date: string; //首次装表日期
  is_remote_meter: boolean; //是否远程表
  last_installation_date: string; //最近装表日期`
  location_description: string; //位置描述
  meter_id: number; //水表id
  meter_usage_id: number; //水表用途类型
  reading_book_id: string; //表册id
  reading_cycle_id: number; //单双朋
  reading_route_id: number; //抄表片区id
}
/*物理水表*/
interface meterType {
  diameter_id: number; //口径id
  factory_id: number; //厂家id
  lead_seal_code: string; //铅封号
  meter_code: string; //表码
  factory_meter_module_id: number; //厂家型号ID
}

interface companyType {
  //企业
}

/*新增账户*/
interface addInfoType {
  user_category_id: number; //账户类型
  use_water_type: number; //用水类别
  files: string; //上传的文件
  contact_id: string; //关联联系人id
  contact: contactType; //联系人
  water_use_region_id: number; //用水区域id
  meter_id: number; //关联水表id
  house_number: string; //房产证编号
  user_meter: userMeterType; //用户水表
  meter: meterType; //物理水表
}

/*联系人*/
interface contactType {
  full_name: string; //全称
  gender: number; //性别
  cell_phone: string; //手机号
  certificate_code: string; //证件号
  certificate_type_id: number; //证件
  email: string; //邮箱
  home_address: string; //家庭住址
  home_address_region_id: number; //家庭住址区域id
}
/*水表类型*/
interface userMeterType {
  first_connection_date: string; //首次装表日期
  is_remote_meter: boolean; //是否远程表
  last_installation_date: string; //最近装表日期`
  location_description: string; //位置描述
  meter_id: number; //水表id
  meter_usage_id: number; //水表用途类型
  reading_book_id: string; //表册id
  reading_cycle_id: number; //单双朋
  reading_route_id: number; //抄表片区id
}
/*物理水表*/
interface meterType {
  diameter_id: number; //口径id
  factory_id: number; //厂家id
  lead_seal_code: string; //铅封号
  meter_code: string; //表码
  factory_meter_module_id: number; //厂家型号ID
}

interface companyType {
  //企业
}

/*新增账户*/
interface addInfoType {
  user_category_id: number; //账户类型
  use_water_type: number; //用水类别
  files: string; //上传的文件
  contact_id: string; //关联联系人id
  contact: contactType; //联系人
  water_use_region_id: number; //用水区域id
  meter_id: number; //关联水表id
  house_number: string; //房产证编号
  user_meter: userMeterType; //用户水表
  meter: meterType; //物理水表
}

interface addCompanyInfoType {
  user_category_id: number; //账户类型
}

interface addCompanyInfoType {
  user_category_id: number; //账户类型
}

interface accountDetailsFace {
  //有部分暂时定义为object类型,后续要改回
  userInfoList: object; //获取账户详情列表
  userPageList: []; //分页查询账户列表
  householdList: selectType[]; //户主信息下拉列表
  contactQueryList: selectType[];
  waterList: selectType[]; //水表信息下拉列表
  total: number;
  pageInfo: object;
  addInfo: addInfoType | {};
  pageInfoMax: object;
  updateHouseInfo: object;
  addUser_category_id: number | string; //新增的账户类型/居民还是企业
  addBasicInfo: object; //新增用户基础信息
  addContact: object; //新增户主信息
  addContactsInfo: object; //新增联系人信息
  addMeter: object; //新增水表
  addUserMeter: any; //新增用户水表
  addFileList: any[]; //新增用户附件
  addCompany: object; //新增企业信息
  currentNumber: number; //表单提交后改变此值来触发下一步
  accountNumber: any; //新建完成之后的账户编号
  meter_dept_id: string; //水表id -- 一般用于新增水表的时候,保存返回值
  loadingList: boolean;
}

export const accountDetailsStore = defineStore({
  id: 'accountDetails-state',
  state: (): accountDetailsFace => ({
    userInfoList: [], //获取账户详情列表
    userPageList: [], //分页查询账户列表
    householdList: [], //户主信息下拉列表
    contactQueryList: [], //企业信息下拉列表
    waterList: [], //水表信息列表
    updateHouseInfo: {}, //更换户主,暂存新户主信息
    total: 0, //总页数
    pageInfo: {
      //分页
      page_no: 1,
      page_size: 10,
    },
    pageInfoMax: {
      //查询所有分页(暂时--后续要改成分页样式)
      page_no: 1,
      page_size: 999,
    },
    loadingList: false, //
    addUser_category_id: '', //新增的账户类型/居民还是企业
    addContactsInfo: {}, //新增联系人信息
    addBasicInfo: {}, //新增用户基础信息
    addCompany: {}, //新增企业信息
    addContact: {}, //新增户主信息
    addUserMeter: null, //新增用户水表
    addMeter: {}, //水表信息
    addFileList: [], // 附件信息
    currentNumber: 0, //表单提交后改变此值来触发下一步
    accountNumber: '', //新建完成之后的账户编号
    meter_dept_id: '', //水表id -- 一般用于新增水表的时候,保存返回值
    addInfo: {},
  }),
  getters: {},
  actions: {
    setUserInfoList(list: {}) {
      //获取到的列表数据
      this.userInfoList = list ? list : {};
    },
    setUserPageList(list: []) {
      //分页查询账户列表
      // console.log("setUserPageList-----",list);
      this.userPageList = list ? list : [];
    },
    setTotal(total: number) {
      //总页数
      this.total = total;
    },
    setPageInfo(pageParams: object) {
      //设置页面数据
      this.pageInfo = pageParams;
    },
    setHouseholdList(holeList: selectType[]) {
      this.householdList = holeList;
    },
    setContactQueryList(contactList: selectType[]) {
      this.contactQueryList = contactList;
    },
    setWaterList(waterArray: selectType[]) {
      this.waterList = waterArray;
    },
    setUpdateHouseInfo(dateObj: object) {
      //更换户主,暂存新户主信息
      this.updateHouseInfo = dateObj;
    },
    /** 新增账户字段 */
    //新增的账户类型/居民还是企业
    setAddUser_category_id(category_id: string) {
      this.addUser_category_id = category_id;
    },
    //新增用户基础信息
    setAddBasicInfo(baseInfo: object) {
      this.addBasicInfo = baseInfo;
    },
    //新增户主信息
    setAddContact(contactObj: object) {
      this.addContact = contactObj;
    },
    //新增联系人信息
    setAddContactsInfo(contactObj: object) {
      this.addContactsInfo = contactObj;
    },
    //新增企业信息
    setAddCompany(contactObj: object) {
      this.addCompany = contactObj;
    },
    //新增水表信息
    setAddMeter(meterObj: object) {
      this.addMeter = meterObj;
    },
    //新增用户水表
    setAddUserMeter(userMeter: any) {
      this.addUserMeter = userMeter;
    },
    //新增附件信息
    setAddFileList(list: any[]) {
      this.addFileList = list;
    },
    //水表id -- 一般用于新增水表的时候,保存返回值
    setMeterDeptId(dept_id: string) {
      this.meter_dept_id = dept_id;
    },

    //表单提交后改变此值来触发下一步
    setCurrentNumber(currentNum: number) {
      // console.log('触发了此值....', currentNum);
      this.currentNumber = currentNum;
    },
    //新建完成之后的账户编号
    setAccountNumber(accountString: string) {
      // console.log('触发了此值111....', accountString);
      this.accountNumber = accountString;
    },

    /** 新增账户字段 end */
    resetState() {
      this.userInfoList = [];
      this.pageInfo = {
        page_no: 1,
        page_size: 10,
      };
    },
    /**
     * @description: 分页请求数据
     */
    async userPageAction(params: object) {
      //分页请求数据
      this.loadingList = true;
      const userPageList = await userPageApi(params);
      this.loadingList = false;
      if (userPageList.code === 0) {
        this.setUserPageList(userPageList.data);
        this.setTotal(userPageList.total);
      } else {
        messageFn('error', userPageList.msg);
      }
    },
    /**
     * @description: 查询账户详情
     */
    async userInfoAction(params: object) {
      //分页请求数据
      const userInfoList = await userInfoApi(params);
      if (userInfoList.code === 0) {
        this.setUserInfoList(userInfoList.data);
        return true;
      } else {
        messageFn('error', userInfoList.msg);
      }
    },
    /**
     * @description: 查询账户详情
     */
    async updateAction(params: object) {
      //分页请求数据
      const update = await updateApi(params);
      if (update.code === 0) {
        messageFn('success', update.msg);
        // this.userPageAction(this.pageInfo);
        return true;
      } else {
        messageFn('error', update.msg);
        return false;
      }
    },

    /**
     * @description: 绑定联系人
     */
    async bindContactAction(params: object) {
      //分页请求数据
      const bindContact = await bindContactApi(params);
      if (bindContact.code === 0) {
        messageFn('success', bindContact.msg);
        // this.userPageAction(this.pageInfo);
        return true;
      } else {
        messageFn('error', bindContact.msg);
      }
    },

    /**
     * @description: 创建账户
     */
    async createAction(params: object) {
      //分页请求数据
      const create = await createApi(params);
      if (create.code === 0) {
        messageFn('success', create.msg);
        this.setAccountNumber(create.data);
        this.userPageAction(this.pageInfo);
        return true;
      } else {
        messageFn('error', create.msg);
        return false;
      }
    },

    /**
     * @description: 注销账户
     */
    async userLogoffAction(params: object) {
      //分页请求数据
      const userLogoff = await userLogoffApi(params);
      if (userLogoff.code === 0) {
        messageFn('success', userLogoff.msg);
        return true;
      } else {
        messageFn('error', userLogoff.msg);
      }
    },
    /**
     * @description: 更改户主
     */
    async userChangeHouseholderAction(params: object) {
      //分页请求数据
      const userChangeHouseholder = await userChangeHouseholderApi(params);
      if (userChangeHouseholder.code === 0) {
        messageFn('success', userChangeHouseholder.msg);
        this.userPageAction(this.pageInfo);
        return true;
      } else {
        messageFn('error', userChangeHouseholder.msg);
      }
    },
    /**
     * @description: 创建联系人
     */
    async userContactCreateAction(params: object) {
      //创建联系人
      const userContactCreate = await userContactCreateApi(params);
      if (userContactCreate.code === 0) {
        messageFn('success', userContactCreate.msg);
        return userContactCreate.data;
      } else {
        messageFn('error', userContactCreate.msg);
        return false;
      }
    },
    /**
     * @description: 联系人是否存在
     */
    async isContactAction(params: object) {
      //创建联系人
      const userContactCreate = await isContactApi(params);
      if (userContactCreate.code === 0) {
        if (userContactCreate.data) {
          messageFn('error', '该联系人已存在，请勿重复新建');
          return false;
        } else {
          return true;
        }
      } else {
        messageFn('error', userContactCreate.msg);
        return false;
      }
    },
    /**
     * @description: 水表是否存在
     */
    async isMeterAction(code: string) {
      //创建联系人
      const userContactCreate = await isMeterApi(code);
      if (userContactCreate.code === 0) {
        if (userContactCreate.data) {
          messageFn('error', '该水表已存在，请勿重复新建');
          return false;
        } else {
          return true;
        }
      } else {
        messageFn('error', userContactCreate.msg);
        return false;
      }
    },
    /**
     * @description: 创建水表
     */
    async meteringCreateAction(params: object) {
      //创建联系人
      const meteringCreate = await meteringCreateApi(params);
      if (meteringCreate.code === 0) {
        this.setMeterDeptId(meteringCreate.data);
        messageFn('success', meteringCreate.msg);
        return true;
      } else {
        messageFn('error', meteringCreate.msg);
        return false;
      }
    },

    /*
     * @description: 条件查询联系人
     */
    async contactQueryAction(params: object) {
      //条件查询联系人
      const contactQuery = await contactQueryApi(params);
      if (contactQuery.code === 0) {
        const newMap = contactQuery.data;
        const newValue = newMap.map((item: object, index: number) => {
          return {
            ...item,
            label: `${item?.full_name ? item?.full_name : ''}/${
              item?.cell_phone ? item?.cell_phone : ''
            }/${item?.certificate_code ? item?.certificate_code : ''}`,
            value: item?.contact_id,
          };
        });
        this.setHouseholdList(newValue);
        return newValue;
      } else {
        messageFn('error', contactQuery.msg);
      }
    },

    /**
     * @description: companyListQueryApi  //条件查询企业
     */
    async companyListQueryAction(params: object) {
      const companyListQuery = await companyListQueryApi(params);
      if (companyListQuery.code === 0) {
        const newMap = companyListQuery.data;
        const newValue = newMap.map((item: object, index: number) => {
          return {
            ...item,
            label: `${item?.company_name}/${item?.tax_id_number}`,
            value: item?.company_id,
          };
        });
        this.setContactQueryList(newValue);
        return newValue;
      } else {
        messageFn('error', companyListQuery.msg);
      }
    },
    /*
     * @description: 获取物理水表分页
     */
    async meteringAdminAction(params: object) {
      //获取物理水表分页
      const meteringAdmin = await meteringAdminApi(params);
      if (meteringAdmin.code === 0) {
        const newMeter = meteringAdmin.data;
        const newMeterValue = newMeter.map((item: object, index: number) => {
          return {
            ...item,
            label: `${item?.meter_code}/${item?.diameter_name}`,
            value: item?.meter_code,
          };
        });
        this.setWaterList(newMeterValue);
        return Promise.resolve(true);
      } else {
        messageFn('error', meteringAdmin.msg);
        return Promise.resolve(false);
      }
    },

    /*
     * @description: 条件查询联系人1
     */
    async contactQueryAction1(params: object) {
      //条件查询联系人
      const contactQuery = await contactQueryApi(params);
      return contactQuery;
    },

    /**
     * @description: userParamsApi  //获取用户列表相关参数
     */
    async userParamsAction() {
      const userParams = await userParamsApi();
      return userParams;
    },
    /**
     * @description: userParamsApi  //获取用户列表相关参数
     */
    async userTagAction() {
      const userParams = await userTagApi();
      return userParams;
    },

    /**
     * @description: regionListApi  //省市区联动对应表
     */
    async regionListAction(params: any) {
      const localStorageObj = {
        1: 'swkj_provinceList',
        2: 'swkj_cityList',
        3: 'swkj_areaList',
        4: 'swkj_streetList'
      }
      if (params.level) {
        const localStorageKey = localStorageObj[params.level]
        const localStorageData = ls.get(localStorageKey) || []
        if (params.level>1 && !params.regionCode) {
          return { code: 0, data: [], msg: '成功' }
        }
        // 省的缓存数据不需要过滤筛选 
        const filterData = (params.level === 1 && localStorageData.length) ? localStorageData : localStorageData.filter(item => item.region_parent_code === params.regionCode)
        if (filterData.length) {
          return {
            code: 0,
            data: filterData,
            msg: '成功'
          }
        } else {
          const requestApi = await regionListApi(params)
          const list = requestApi.data
          list?.length && ls.set(localStorageKey,localStorageData.concat(list))
          return requestApi
        }
      } else {
        const requestApi = await regionListApi(params)
        return requestApi
      }
    },
    /**
     * @description: 查询账户详情
     */
    async queryUserInfoAction(params: object) {
      return new Promise(async (resolve, reject) => {
        const r = await userInfoApi(params);
        if (r.code === 0) {
          resolve(r.data);
        } else {
          messageFn('error', r.msg);
          reject(r.msg);
        }
      });
    },
    /**
     * @description: 账户解绑水表
     */
    async unbindMeterAction(params: object) {
      const r = await unbindMeterApi(params);
      if (r.code === 0) {
        messageFn('success', '解绑成功');
        return Promise.resolve(r.data);
      } else {
        messageFn('error', r.msg);
        return Promise.reject(r.msg);
      }
    },
    /**
     * @description: 账户解绑联系人
     */
    async unbindContactAction(params: object) {
      const r = await unbindContactApi(params);
      if (r.code === 0) {
        messageFn('success', '解绑成功');
        return Promise.resolve(r.data);
      } else {
        messageFn('error', r.msg);
        return Promise.reject(r.msg);
      }
    },
    /**
     * @description: 账户绑定水表
     */
    async bindMeterApiAction(params: object) {
      const r = await bindMeterApi(params);
      if (r.code === 0) {
        messageFn('success', '绑定成功');
        return Promise.resolve(r.data);
      } else {
        messageFn('error', r.msg);
        return Promise.reject(r.msg);
      }
    },
    /**
     * @description: 获取该账户的所有业务记录数量
     */
    async getCustomerUserRecordAction(params: any) {
      const r = await getCustomerUserRecordApi(params);
      if (r.code === 0) {
        return Promise.resolve(r.data);
      } else {
        messageFn('error', r.msg);
        return Promise.reject(r.msg);
      }
    },
  },
});
